#!/usr/bin/env python
from google.appengine.ext import db

import TopicM
import LectureM
import QuestionM

class PostClassStats(db.Model):
    
    class TopicStats(db.Model):
        topic=db.ReferenceProperty(TopicM.Topic)
        startDate=db.DateTimeProperty(auto_now_add=True)
        # stats
        understand=db.IntegerProperty()
        total=db.IntegerProperty()
        
    class QuestionStats(db.Model):
        question=db.ReferenceProperty(QuestionM.Question)
        startDate=db.DateTimeProperty(auto_now_add=True)
        answersStats=db.ListProperty(int, default=[])
    
    # identifiers
    lecture=db.ReferenceProperty(LectureM.Lecture)
    # date:
    startDate=db.DateTimeProperty(auto_now_add=True)
    endDate=db.DateTimeProperty(auto_now=True)
    # statistics:
    
    # Should be moved into one Class - Temporary Solution
    # Simulating Map (Dictionary)
    topicsStats=db.ListProperty(db.Key, default=[])
    topicsStatsKeys=db.ListProperty(db.Key, default=[])
    
    def addTopicStats(self,topic, total, understand):
        topicStats = None
        topicIndex = -1
        
        # note: I'm an idiot!
        try: 
            topicIndex=self.topicsStatsKeys.index(topic.key())
        except:
            pass
#        for index, key in enumerate(self.topicsStatsKeys):
#            if key == str(topic.key()):
#                topicIndex=index

        if topicIndex == -1:
            topicStats=self.TopicStats(topic=topic)
            topicStats.put()
            self.topicsStats.append(topicStats.key())
            self.topicsStatsKeys.append(topic.key())
        else:
            topicStats=self.TopicStats.get(self.topicsStats[topicIndex])
        
        # update data
        topicStats.understand=understand
        topicStats.total=total
        topicStats.put()
        
    def getTopicStats(self, topic):
        topicIndex = -1
        try: 
            topicIndex=self.topicsStatsKeys.index(topic.key())
        except:
            return None
        
        topicStats=self.TopicStats.get(self.topicsStats[topicIndex])
        
        return {'total': topicStats.total, 'understand': topicStats.understand}
       
        
    questionsStats=db.ListProperty(db.Key, default=[])
    questionsStatsKeys=db.ListProperty(db.Key, default=[])
    
    def addQuestionStats(self,question,answersVotes):
        questionStats = None
        questionIndex = -1
        
        try: 
            questionIndex=self.questionStatsKeys.index(question.key())
        except:
            pass
#        for index, key in enumerate(self.topicsStatsKeys):
#            if key == str(topic.key()):
#                topicIndex=index

        if questionIndex == -1:
            questionStats=self.QuestionStats(question=question)
            questionStats.put()
            self.questionsStats.append(questionStats.key())
            self.questionsStatsKeys.append(question.key())
        else:
            questionStats=self.QuestionStats.get(self.questionStats[questionIndex])
        
        # update data
        for index, voteCount in enumerate(answersVotes):
            questionStats.answersStats.append(voteCount)
        
        questionStats.put()
    
    def getQuestionStats(self, question):
        questionIndex = -1
        try: 
            questionIndex=self.questionsStatsKeys.index(question.key())
        except:
            return None
        
        questionStats=self.QuestionStats.get(self.questionsStats[questionIndex])
        return questionStats.answersStats
    
def saveVotesStats(lecture, topic, total, understand):
    postClass=_getLastPostClass(lecture)
    postClass.addTopicStats(topic,total,understand)
    postClass.put()

def saveQuestionStats(lecture, question, answersVotes):
    postClass=_getLastPostClass(lecture)
    postClass.addQuestionStats(question,answersVotes)
    postClass.put()

def getTopicsStats(postClassKey):
    postClass=_getPostClassByKey(postClassKey)
    
    def mapper(topicStatsKey):
        topicStats=PostClassStats.TopicStats.get(topicStatsKey)
        topicStatsDic = {
               'topic' : topicStats.topic.name,
               'start_date' : str(topicStats.startDate),
               'understand' : topicStats.understand,
               'total' : topicStats.total
           }
        return topicStatsDic
    
    return map(mapper,postClass.topicsStats)

def getQuestionList(postClassKey):
    postClass=_getPostClassByKey(postClassKey)
    
    def mapper(questionKey):
        question=QuestionM.getQuestionByKey(questionKey)
        questionDic = {
               'name' : question.name,
               'key' : str(question.key()),
           }
        return questionDic
    
    return map(mapper,postClass.questionsStatsKeys)

def getQuestionsStats(postClassKey):
    postClass=_getPostClassByKey(postClassKey)
    
    def mapper(questionStatsKey):
        questionStats=PostClassStats.QuestionStats.get(questionStatsKey)
        questionStatsDic = {
               'question' : questionStats.question.name,
               'start_date' : questionStats.startDate,
               'answers_stats' : questionStats.answerStats,
           }
        return questionStatsDic
    
    return map(mapper,postClass.questionsStats)

def addPostClass(lecture):
    postClass=PostClassStats(lecture=lecture)
    postClass.put()

def getPostClassList(lecture):
    postClassQuery=db.Query(PostClassStats).filter('lecture =',lecture).order('startDate')
    
    def mapper(postClass):
        postClassDic = {
               'key' : str(postClass.key()),
               'date' : str(postClass.startDate),
           }
        return postClassDic

    return map(mapper,postClassQuery)

def getQuestionStats(postClassKey, questionKey):
    postC=_getPostClassByKey(postClassKey)
    question=QuestionM.getQuestionByKey(questionKey)
    answersStats=postC.getQuestionStats(question)
    answersText=QuestionM.getQuestionAnswers(questionKey)
    
    def mapper(answersText,answersStats):
        statsDic = {
               'answer' : answersText,
               'stats' : str(answersStats),
           }
        return statsDic
    
    return map(mapper,answersText,answersStats)

def getQuestionsPer(postClassKey):
    postC=_getPostClassByKey(postClassKey)
    questionsStats=postC.questionsStats
    
    def mapper(questionStatsKey):
        questionStats = postC.QuestionStats.get(str(questionStatsKey))
        question = questionStats.question
        rightIndex = question.rightAnswer
        total=0
        for i in questionStats.answersStats:
            total=total + i
            
        statsDic = {
               'name' : question.name,   
               'right' : questionStats.answersStats[rightIndex],
               'total' : total,
           }
        return statsDic
    
    return map(mapper,questionsStats)

def getQuestionsKeys(postClassKey):
    postC=_getPostClassByKey(postClassKey)
    return postC.questionsStatsKeys

def _getPostClassByKey(key):
    try:
        postClass=PostClassStats.get(key)
        return postClass
    except:
        return None

def _getLastPostClass(lecture):
    postClassQuery=db.Query(PostClassStats).filter('lecture =',lecture).order('-startDate')
    return postClassQuery.get()